const sqlite3 = require('sqlite3').verbose();
const path = require('path');

class SqliteDB {
    constructor() {
        this.db = new sqlite3.Database(path.join(__dirname, '../database.sqlite3'));
    }

    /**
     * 创建表
     * @param tableName 表名
     * @param columns 列
     */
    createTable(tableName, columns) {
        const columnDefinitions = columns.map(column => `${column.name} ${column.type}`).join(', ');
        const query = `create table if not exists ${tableName} (${columnDefinitions})`;
        this.db.run(query);
    }

    /**
     * 插入数据
     * @param tableName 表名
     * @param data 数据
     */
    insertData(tableName, data) {
        const columns = Object.keys(data).join(', ');
        const placeholders = Object.keys(data).map(() => '?').join(', ');
        const values = Object.values(data);
        const query = `insert into ${tableName} (${columns}) values (${placeholders})`;
        this.db.run(query, values);
    }

    /**
     * 更新数据
     * @param tableName 表名
     * @param data 数据
     * @param condition 条件
     */
    updateData(tableName, data, condition) {
        const setClause = Object.keys(data).map(column => `${column} = ?`).join(', ');
        const values = Object.values(data);
        const query = `update ${tableName} set ${setClause} where ${condition}`;
        this.db.run(query, values);
    }

    /**
     * 删除数据
     * @param tableName 表名
     * @param condition 条件
     */
    deleteData(tableName, condition) {
        const query = `delete from ${tableName} where ${condition}`;
        this.db.run(query);
    }

    executeQuery(query, params, cb) {
        this.db.all(query, params, (err, rows) => {
            if (err) {
                console.error(err);
                cb(err);
            } else {
                cb(rows);
            }
        });
    }

    closeConnection() {
        this.db.close();
    }
}

module.exports = SqliteDB;
